// pages/user/user.js
const app = getApp()
var help = require('../../utils/help.js');
var login = require('../../utils/login.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageUrl: app.data.imageUrl,
    data: {
      username: '平凡的洋葱',
      avatar: '',
      usable_bonus: 0
    },
    info: {},
    showSync: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 4
      })
    }

    console.log(app.data.userInfo)
    if (!app.data.userInfo) {
      app.getPhoneNumber = () => {
        that.loadData();
        that.setData({
          data: app.data.userInfo,
          showSync: !app.data.wxUserInfo ? true : false
        })
        app.getPhoneNumber = null;
      }
      login.getUserInfo(app);
    } else {
      this.loadData();
    }

    this.setData({
      data: app.data.userInfo,
      showSync: !app.data.wxUserInfo ? true : false
    })
  },

  /**
   * 加载数据
   */
  loadData: function () {
    var that = this;
    var url = app.data.apiUrl + 'User/index';
    var data = {
      token: app.data.userInfo ? app.data.userInfo.token : '',
    };
    help.get(url, data, that, function (res, that) {
      wx.hideLoading()
      var result = res.data;
      // console.log(result);
      if (result.code == 1) {
        that.setData({
          info: result.data,
          showSync: app.data.wxUserInfo ? false : true
        })
        app.data.mobile = result.data.mobile
        // 此处是为了修复之前没有unionid的用户数据
        if (typeof (result.data.unionid) == 'undefined' || result.data.unionid == '') {
          app.getPhoneNumber = () => {
            app.getPhoneNumber = null;
          }
          login.getUserInfo(app);
        }
      } else if (result.code == 401) {
        help.msg('登录已失效，正在重新登录...')
        // 重新检测登录状态
        login.getUserInfo(app);
        return false;
      } else {
        help.msg(result.msg)
        return false;
      }
    });
  },
  /**
   * 刷新微信个人信息
   */
  syncWxUserInfo: function (e) {
    var that = this;
    wx.showLoading({
      title: '正在获取',
    })
    if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
      //拒绝授权
      wx.hideLoading()
      return false;
    } else {
      //同意授权
      app.data.wxUserInfo = e.detail.userInfo;
      wx.setStorageSync('wxUserInfo', app.data.wxUserInfo)
      console.log(app.data.wxUserInfo)
      wx.request({
        url: app.data.apiUrl + 'Weapp/profile',
        method: 'POST',
        data: {
          token: app.data.userInfo ? app.data.userInfo.token : '',
          nickname: app.data.wxUserInfo.nickName,
          avatar: app.data.wxUserInfo.avatarUrl,
          gender: app.data.wxUserInfo.gender
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          wx.hideLoading()
          if (res.data.code == 1) {
            that.loadData();
            wx.showToast({
              title: '授权成功',
              icon: 'success',
              duration: 2000
            })
            login.getUserInfo(app);
          } else if (result.code == 401) {
            help.msg('登录已失效，正在重新登录...')
            // 重新检测登录状态
            login.getUserInfo(app);
            return false;
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }

        },
        fail: function (e) {
          wx.hideLoading()
          wx.showModal({
            content: '网络不畅，请检测网络后重试',
            confirmText: "确认",
            cancelText: "取消",
            // showCancel: false, // 不显示取消按钮
            success: function (res) {
              if (res.confirm) {

              } else {
              }
            }
          });
        }
      })
    }
  },


  // 收货地址
  goAddress: function()
  {
    help.goUrl('/pages/shopcart/address/address')
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})